package com.dogsong.liteflow.editor.util;

import com.yomahub.liteflow.parser.constant.ReadType;
import com.yomahub.liteflow.parser.sql.read.SqlRead;
import com.yomahub.liteflow.parser.sql.read.SqlReadFactory;
import com.yomahub.liteflow.parser.sql.read.impl.ChainRead;
import com.yomahub.liteflow.parser.sql.read.vo.ChainVO;
import com.yomahub.liteflow.parser.sql.util.LiteFlowJdbcUtil;
import com.yomahub.liteflow.parser.sql.vo.SQLParserVO;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;

/**
 * sql连接工厂
 *
 * @author: Young
 * @date: 2024/12/17
 */
@Slf4j
public class SqlConnectFactory {

    public static SQLParserVO getSqlConfig(){
        return SqlConfigHolder.config;
    }

    public static Connection getConn(){
        return LiteFlowJdbcUtil.getConn(SqlConnectFactory.getSqlConfig());
    }

    private static class SqlConfigHolder{
        public static SQLParserVO config;

        static {
            try {
                SqlRead<ChainVO> sqlRead = SqlReadFactory.getSqlRead(ReadType.CHAIN);
                if (sqlRead != null) {
                    ChainRead chainRead = (ChainRead) sqlRead;
                    if (chainRead != null && chainRead.config != null) {
                        config = chainRead.config;
                    } else {
                        config = new SQLParserVO();
                        log.warn("LiteFlow SQL配置为空，使用默认配置");
                    }
                } else {
                    // 如果获取不到sqlRead，使用默认配置
                    config = new SQLParserVO();
                    log.warn("无法获取LiteFlow SQL读取器，使用默认配置");
                }
            } catch (Exception e) {
                // 处理可能的空指针异常
                config = new SQLParserVO();
                log.error("获取LiteFlow SQL配置时发生异常，使用默认配置", e);
            }
        }
    }
}
